(function ($) {
    var page = "dialogue";
    layui.use(['element', 'form', 'layer', 'laytpl'], function () {
        var model = $(".dialogue-content");
        var layer = layui.layer;
        var form = layui.form;
        var laytpl = layui.laytpl;

        //是否有任务在执行
        var processing = false;

        //富文本编辑器
        var umEditor;
        var authors = loadAuthors();

        //渲染作者下拉框
        renderAuthorOpts();
        var statusCollections = [
            {"code": "01", "description": "上线"},
            {"code": "00", "description": "下线"}
        ];
        form.render();


        var table = $(".dialogue-table").table({
            columns: [
                {
                    "name": "id",
                    "display": "ID"
                },
                {
                    "name": "title",
                    "display": "对话标题"
                },
                {
                    "name": "author",
                    "display": "作者"
                },
                {
                    "name": "tag",
                    "display": "标签"
                },
                {
                    "name": "readAmount",
                    "display": "阅读量"
                },
                {
                    "name": "status",
                    "display": "状态",
                    "render": function (rowData) {
                        if (rowData.status == "01") {
                            return "<font color='#00bfff'>上线</font>";
                        } else {
                            return "<font color='gray'>下线</font>";
                        }
                    }
                },
                // {
                //     "name": "expireTime",
                //     "display": "过期时间",
                //     "render": function (rowData) {
                //         rowData.expireTimeInHour = (rowData.expireTime / 60).toFixed(0);
                //         return rowData.expireTimeInHour + "小时";
                //     }
                // },
                {
                    "display": "操作",
                    render: function (rowData) {
                        var ret = "<div class='opt-btn-group'>";
                        if (rowData.status == "01") {
                            ret += "<span class='update-status-item'><i class=\"layui-icon\">&#xe857;</i><font color='red'>下线</font></span>";
                        } else {
                            ret += "<span class='update-status-item'><i class=\"layui-icon\">&#xe857;</i><font color='#00bfff'>上线</font></span>";
                        }
                        ret += "<span class='edit-item'><i class=\"layui-icon\">&#xe642;</i>编辑</span>" +
                            /*"<span class='delete-item'><i class=\"layui-icon\">&#xe640;</i>删除</span>" +*/
                            "<span class='preview-item'><i class=\"layui-icon\">&#xe609;</i>预览</span>" +
                            "</div>";
                        return ret;
                    }
                }
            ],
            url: "/hycj/news",
            showTitle: false,
            formatData: function (data) {
                return data.datas;
            },
            params: {
                channelId: 3
            }
        });

        //编辑对话框
        model.on("click", ".edit-item", function (e) {
            var rowData = table.getRowData($(e.target).closest("tr"));
            $.getJsonData("/hycj/news/" + rowData.id).done(function (data) {
                //data.datas.expireTimeInHour = (data.datas.expireTime / 60).toFixed(0);
                laytpl($("#dialogueForm").html()).render({
                    model: "updateDialogueForm",
                    authors: authors,
                    statusCollections: statusCollections,
                    data: data.datas
                }, function (content) {
                    layer.open({
                        type: 1,
                        title: "更新对话",
                        content: content,
                        offset: 'auto',
                        area: '80%',
                        maxHeight: app.clientHeight() - 50,
                        success: function () {
                            form.render();
                            if (umEditor) {
                                umEditor.destroy();
                                umEditor = UM.getEditor('content');
                            } else {
                                umEditor = UM.getEditor('content');
                            }
                            umEditor.addListener("afterfullscreenchange",function(e){
                                var flag = umEditor._edui_fullscreen_status;
                                if(!flag){
                                    umEditor.setHeight(200);
                                }
                            });
                            $("[name='tag']").tagsinput({
                                tagClass: 'big',
                                confirmKeys: [44, 65292, 9, 32]
                            });
                        }
                    });
                });
            });
        });

        //创建对话框
        model.on("click", ".create-item", function (e) {
            laytpl($("#dialogueForm").html()).render({
                model: "addDialogueForm",
                authors: authors,
                statusCollections: statusCollections,
                data: {}
            }, function (content) {
                layer.open({
                    type: 1,
                    title: "创建对话",
                    content: content,
                    offset: 'auto',
                    area: '80%',
                    maxHeight: app.clientHeight() - 50,
                    success: function () {
                        form.render();
                        if (umEditor) {
                            umEditor.destroy();
                            umEditor = UM.getEditor('content');
                        } else {
                            umEditor = UM.getEditor('content');
                        }
                        umEditor.addListener("afterfullscreenchange",function(e){
                            var flag = umEditor._edui_fullscreen_status;
                            if(!flag){
                                umEditor.setHeight(200);
                            }
                        });
                        $("[name='tag']").tagsinput({
                            tagClass: 'big',
                            confirmKeys: [44, 65292, 9, 32]
                        });
                    }
                });
            });
        });

        //删除对话框
        model.on("click", ".delete-item", function (e) {
            var layer = layui.layer;
            var selectedData = table.getRowData($(e.target).closest("tr"));
            layer.msg('您确认删除<br>' + selectedData.title, {
                time: 5000, //5s后自动关闭
                btn: ['确认', '取消']
                , btn1: function (index, layero) {
                    $.getJsonData("/hycj/news"
                        , {id: selectedData.id}
                        , {type: "Delete"})
                        .done(function () {
                            layer.msg("删除完成");
                            table.refresh();
                        }).fail(function () {
                        layer.msg("删除失败, 请稍后重试!");
                    });
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });

        //上下线对话框
        model.on("click", ".update-status-item", function (e) {
            var layer = layui.layer;
            var selectedData = table.getRowData($(e.target).closest("tr"));
            var tipInfo = "下线";
            //下线改上线
            if (selectedData.status == "00") {
                tipInfo = "上线";
                selectedData.status = "01";
            } else {
                //上线改下线
                selectedData.status = "00";
            }
            //作者保存时，使用author字段
            selectedData.author = selectedData.author.id;
            layer.msg('您确认' + tipInfo + '<br>' + selectedData.title, {
                time: 5000, //5s后自动关闭
                btn: ['确认', '取消']
                , btn1: function (index, layero) {

                    $.getJsonData("/hycj/news", selectedData, {type: "Put"}).done(function (data) {
                        if (data.code != "200") {
                            layer.msg('操作失败', {icon: 2});
                        } else {
                            app.showSuccess();
                            table.refresh();
                        }
                        processing = false;
                    }).fail(function () {
                        processing = false;
                    });
                }
                , btn2: function (index, layero) {
                    layer.close(index);
                }
            });
        });


        //预览
        model.on("click", ".preview-item", function (e) {
            var selectedData = table.getRowData($(e.target).closest("tr"));
            window.open("/article-preview.html?id=" + selectedData.id);
        });

        //搜索
        form.on('submit(searchDialogueForm)', function (data) {
            if (!data.form) {
                return false
            }
            table.refresh(data.field);
            return false;
        });

        //新增
        form.on('submit(addDialogueForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            if (data.field.content.length > 409600) {
                layer.msg("内容过长（最长409600个字符）", {icon: 2});
                return false;
            }

            processing = true;

            $.getJsonData("/hycj/news", data.field, {type: "Post"}).done(function (data) {
                if (data.code != "200") {
                    layer.msg('保存失败', {icon: 2});
                } else {
                    layer.msg('操作成功', {icon: 6});
                    layer.closeAll();
                    table.refresh();
                }

                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });

        //更新
        form.on('submit(updateDialogueForm)', function (data) {
            if (processing || !data.form) {
                return false
            }
            if (data.field.content && data.field.content.length > 409600) {
                layer.msg("内容过长（最长409600个字符）", {icon: 2});
                return;
            }

            processing = true;
            $.getJsonData("/hycj/news", data.field, {type: "Put"}).done(function (data) {
                if (data.code != "200") {
                    layer.msg('操作失败', {icon: 2});
                } else {
                    app.showSuccess();
                    table.refresh();
                }
                processing = false;
            }).fail(function () {
                processing = false;
            });
            return false;
        });

        function loadAuthors() {
            var data = [];
            $.getJsonData("/hycj/users/getMediaUser?pageNum=1&pageSize=1000", {}, {
                type: "Get",
                async: false
            }).done(function (result) {
                data = result.datas.items;
            })
            return data;
        }


        /**
         * 渲染搜索表单中的作者下拉框
         */
        function renderAuthorOpts() {
            app.renderSelectOptionsTemplate(authors, '', "id", "displayName", true).done(function (content) {
                $("#searchDialogueForm [name='author']").append(content);
                form.render();
            });
        }

        form.verify({
            expireTime: function (value, item) {
                var expireTimeIntVal;
                try {
                    expireTimeIntVal = parseInt(value)
                } catch (error) {
                    return "过期时间只能为数字";
                }
                if (expireTimeIntVal < 6 || expireTimeIntVal >= 24) {
                    return "过期时间只能为6（包括）到24（不包括）小时";
                }
            },
            positiveInteger: function (value, item) {//正整数
                if (value) {
                    try {
                        if (parseInt(value) != value || value < 0) {
                            return "请输入正整数";
                        }
                    } catch (error) {
                        return "请输入正整数";
                    }
                }
            }
        });

        app.bindPageEvents(page, function () {
            //上传封面
            $(document).on("click", ".dialogue-form .add-image", function (e) {
                var $addBtn = $(e.currentTarget);
                moon.uploader({
                    //上传成功的回调，回调数据为文件上传的路径。格式如下：[{path:xxx},{path:xxx}]
                    callback: function (uploadRet) {
                        var uploadItem = uploadRet[0];
                        $addBtn.closest(".image-item-container").html("<img src=\"" + uploadItem.path + "\" class=\"image-item add-image\"/>");
                        $("[name='image']").val(uploadItem.path);
                    }
                });
            });

            /**
             * 重置表单
             */
            $(document).on("click", ".dialogue-form :reset", function (e) {
                umEditor.setContent("");
                $(".dialogue-image").html("<i class=\"layui-icon image-placeholder add-image\">&#xe60d;</i>");
                $("[name='tag']").tagsinput('removeAll');
            });
        });
    });
})(jQuery);